package com.leenleda.ips.util;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.BuildConfig;
import com.leenleda.ips.activity.WebActivity;
import com.leenleda.ips.receiver.Constant;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

public class MyCrash implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        saveCrashInfoToFile(throwable);//保存错误报告文件
        String errorMessage=throwable.getMessage();
        Log.e("crashStr","====errorMessage====" + errorMessage);
        Log.e("crashStr","====throwable====" + throwable);
        UShared.putString(Constant.CRASH_TAG, errorMessage);

        if (Constant.APP_RESTART){
//        Toast.makeText(MyApplication.GetInstance(), "errorMessage:" + errorMessage, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(BaseActivity.getForegroundActivity(), WebActivity.class);
            PendingIntent restartIntent = PendingIntent.getActivity(
                    BaseActivity.getForegroundActivity(), UUID.randomUUID().hashCode(), intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            //退出程序
            // 1秒钟后重启应用
            AlarmManager mgr = (AlarmManager)BaseActivity.getForegroundActivity().getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 5000,
                    restartIntent);
        }
        // 杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());

    }


    /**
     * 获取错误报告文件路径
     *
     * @param ctx
     * @return
     */
    public static String[] getCrashReportFiles(Context ctx) {
        File filesDir = new File(getCrashFilePath(ctx));
        String[] fileNames = filesDir.list();
        int length = fileNames.length;
        String[] filePaths = new String[length];
        for (int i = 0; i < length; i++) {
            filePaths[i] = getCrashFilePath(ctx) + fileNames[i];
        }
        return filePaths;
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return
     */
    private void saveCrashInfoToFile(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        String result = info.toString();
        printWriter.close();
        StringBuilder sb = new StringBuilder();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
        String now = sdf.format(new Date());
        sb.append("TIME:").append(now);//崩溃时间
        //程序信息
        sb.append("\nAPPLICATION_ID:").append(BuildConfig.APPLICATION_ID);//软件APPLICATION_ID
        sb.append("\nVERSION_CODE:").append(BuildConfig.VERSION_CODE);//软件版本号
        sb.append("\nVERSION_NAME:").append(BuildConfig.VERSION_NAME);//VERSION_NAME
        sb.append("\nBUILD_TYPE:").append(BuildConfig.BUILD_TYPE);//是否是DEBUG版本
        //设备信息
        sb.append("\nMODEL:").append(android.os.Build.MODEL);
        sb.append("\nRELEASE:").append(Build.VERSION.RELEASE);
        sb.append("\nSDK:").append(Build.VERSION.SDK_INT);
        sb.append("\nEXCEPTION:").append(ex.getLocalizedMessage());
        sb.append("\nSTACK_TRACE:").append(result);
        LogUtils.e("getStrData", "=====app_error=====1====" + sb);
        UShared.putString("app_error", sb.toString());
        try {
            FileWriter writer = new FileWriter(getCrashFilePath(BaseActivity.getForegroundActivity()) + now + ".txt");
            writer.write(sb.toString());
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件夹路径
     *
     * @param context
     * @return
     */
    private static String getCrashFilePath(Context context) {
        String path = null;
        try {
            path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/"
//                    + context.getResources().getString(R.string.app_name) + "/Crash/";
                    + "LELDIPS/Crash/";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("--MyCrash--", "getCrashFilePath: " + path);
        return path;
    }
}


